package cn.ug.product.service.impl;

import cn.ug.aop.RemoveCache;
import cn.ug.aop.SaveCache;
import cn.ug.bean.base.DataTable;
import cn.ug.core.ensure.Ensure;
import cn.ug.product.bean.GoldPriceBaselineBean;
import cn.ug.product.mapper.GoldPriceBaselineMapper;
import cn.ug.product.mapper.entity.GoldPriceBaseline;
import cn.ug.product.service.GoldPriceBaselineService;
import cn.ug.service.impl.BaseServiceImpl;
import cn.ug.util.BigDecimalUtil;
import cn.ug.util.UF;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.dozer.DozerBeanMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import static cn.ug.config.CacheType.OBJECT;
import static cn.ug.config.CacheType.SEARCH;

/**
 * @author kaiwotech
 */
@Service
public class GoldPriceBaselineServiceImpl extends BaseServiceImpl implements GoldPriceBaselineService {
	
	@Resource
	private GoldPriceBaselineMapper goldPriceBaselineMapper;

	@Resource
	private DozerBeanMapper dozerBeanMapper;

	@Override
	@RemoveCache(cleanAll = true)
	public int saveOrUpdate(GoldPriceBaselineBean entityBean) {
		// 数据完整性校验
		if(null == entityBean || null == entityBean.getGoldPrice() || null == entityBean.getLimit()) {
			Ensure.that(true).isTrue("00000002");
		}
		// 计算最大值和最小值
		BigDecimal maxLimit = BigDecimalUtil.add(new BigDecimal("100"), entityBean.getLimit());
		BigDecimal minLimit = BigDecimalUtil.subtract(new BigDecimal("100"), entityBean.getLimit());
		maxLimit = BigDecimalUtil.to5Point(maxLimit.divide(new BigDecimal("100")));
		minLimit = BigDecimalUtil.to5Point(minLimit.divide(new BigDecimal("100")));
		entityBean.setMaxPrice(BigDecimalUtil.multiply(entityBean.getGoldPrice(), maxLimit));
		entityBean.setMinPrice(BigDecimalUtil.multiply(entityBean.getGoldPrice(), minLimit));

		GoldPriceBaselineBean lastBean = findLastByTime();
		if(null == lastBean) {
			// 新增
			GoldPriceBaseline entity = dozerBeanMapper.map(entityBean, GoldPriceBaseline.class);
			if(StringUtils.isBlank(entity.getId())) {
				entity.setId(UF.getRandomUUID());
			}
			int rows = goldPriceBaselineMapper.insert(entity);
			Ensure.that(rows).isLt(1,"00000005");
		} else {
			String[] ids = {lastBean.getId()};

			int rows = goldPriceBaselineMapper.updateByPrimaryKeySelective(
					getParams()
							.put("id", ids)
							.put("goldPrice", entityBean.getGoldPrice())
							.put("limit", entityBean.getLimit())
							.put("maxPrice", entityBean.getMaxPrice())
							.put("minPrice", entityBean.getMinPrice())
							.put("description", entityBean.getDescription())
							.toMap()
			);
			Ensure.that(rows).isLt(1,"00000005");
		}

        return 0;
	}

	@Override
	@RemoveCache(cleanSearch = true, cleanObjectByKeyPosition = 0)
	public int delete(String id) {
		if(StringUtils.isBlank(id)) {
			return 0;
		}

		return goldPriceBaselineMapper.delete(id);
	}

	@Override
	@RemoveCache(cleanSearch = true, cleanObjectByKeyPosition = 0)
	public int deleteByIds(String[] id){
		if(id == null || id.length<=0){
			return 0;
		}

		return goldPriceBaselineMapper.deleteByIds(id);
	}

	@Override
	@SaveCache(cacheType = OBJECT)
	public GoldPriceBaselineBean findById(String id) {
		if(StringUtils.isBlank(id)) {
			return null;
		}

		GoldPriceBaseline entity = goldPriceBaselineMapper.findById(id);
		if(null == entity) {
			return null;
		}

		GoldPriceBaselineBean entityBean = dozerBeanMapper.map(entity, GoldPriceBaselineBean.class);
		entityBean.setAddTimeString(UF.getFormatDateTime(entity.getAddTime()));
		entityBean.setModifyTimeString(UF.getFormatDateTime(entity.getModifyTime()));
		return entityBean;
	}

    @Override
    public GoldPriceBaselineBean findLastByTime() {
        DataTable<GoldPriceBaselineBean> dataTable = query("add_time", "desc", 1, 1);
        if(null == dataTable || null == dataTable.getDataList() || dataTable.getDataList().isEmpty()) {
            return null;
        }
        return dataTable.getDataList().get(0);
    }

    @Override
	@SaveCache(cacheType = SEARCH)
	public DataTable<GoldPriceBaselineBean> query(String order, String sort, int pageNum, int pageSize) {
		Page<GoldPriceBaselineBean> page = PageHelper.startPage(pageNum, pageSize);
		List<GoldPriceBaselineBean> list = query(order, sort);
		return new DataTable<>(page.getPageNum(), page.getPageSize(), page.getTotal(), list);
	}

	/**
	 * 获取数据列表
	 * @param order			排序字段
	 * @param sort			排序方式 desc或asc
	 * @return				列表
	 */
	private List<GoldPriceBaselineBean> query(String order, String sort){
		List<GoldPriceBaselineBean> dataList = new ArrayList<>();
		List<GoldPriceBaseline> list = goldPriceBaselineMapper.query(getParams().toMap());
		for (GoldPriceBaseline o : list) {
			GoldPriceBaselineBean objBean = dozerBeanMapper.map(o, GoldPriceBaselineBean.class);
			objBean.setAddTimeString(UF.getFormatDateTime(o.getAddTime()));
			objBean.setModifyTimeString(UF.getFormatDateTime(o.getModifyTime()));
			dataList.add(objBean);
		}
		return dataList;
	}

}

